/* @flow */
import React from 'react';

import { createAction, createActions, handleActions, type ActionType } from 'redux-actions';
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects';
import { SagaActionType, REQUEST, SUCCESS, FAILURE, type sagaType } from 'lib/sagaUtil';
import * as thingApis from 'lib/api/things';

import produce from 'immer';
import { Map, fromJS } from 'immutable';

/* ACTION TYPES */
// classify
const LOAD_CLASSIFY = SagaActionType('thing/LOAD_CLASSIFY');
const CHANGE_CLASSIFY = 'thing/CHANGE_CLASSIFY';
// contexts
const LOAD_CONTEXTS = 'thing/LOAD_CONTEXTS';
// things
const LOAD_THINGS = 'thing/LOAD_THINGS';
const CHANGE_THING = 'thing/CHANGE_THING';
// inbox
const LOAD_INBOX = 'thing/LOAD_INBOX';

/* ACTION PAYLOADS */
type changeClassifyValuePayload = {
  id: string,
  value: string,
};
type Thing = {
  id: string,
  title: string,
  time: {
    createdTime: number,
    updatedTime: number,
    completedTime: number,
    estimatedTime: number,
    deferUntilTime: number,
    dueTime: number,
  },
  repeat: {
    type: string,
    nextDeferedTime: number,
    nextDueTime: number,
  },
  classify: {
    type: string,
    title: string,
    fullTitle: string,
  },
  parentThing: {
    id: string,
    title: string,
    fullTitle: string,
  },
  context: string,
  status: string,
  flaged: string,
  note: string,
};

type Context = {
  id: string,
  pid: string,
  level: number,
  contextType: 'context' | 'pause' | 'delay' | 'other',
  title: string,
  createdTime: number,
  updatedTime: number,
};
type ThingSimple = {
  pid: string,
  id: string,
  title: string,
  level: number,
  index: number,
  createdTime: number,
  updatedTime: number,
};
export type ClassifySimple = {
  pid: string,
  id: string,
  title: string,
  level: number,
  classifyType: 'classify' | 'action',
  actionType: 'parallet' | 'flow' | 'single' | 'other',
  createdTime: number,
  updatedTime: number,
};
/* EXPORTING ACTION CREATORS / ACTION CREATORS TYPES */
export interface ThingsActionCreators {
  loadClassify(payload: ClassifySimple): any;
  changeClassify(payload: changeClassifyValuePayload): any;
}

export const actionCreators: ThingsActionCreators = {
  loadClassify: createAction(LOAD_CLASSIFY.REQUEST, (payload: ClassifySimple) => payload),
  changeClassify: createAction(CHANGE_CLASSIFY, (payload: changeClassifyValuePayload) => payload),
};
/* ACTION FLOW TYPES */
type LoadClassifyAction = ActionType<typeof actionCreators.loadClassify>;
type ChangeClassifyAction = ActionType<typeof actionCreators.changeClassify>;
/* State Types */

export type Things = {
  classify: {
    isopenRange: { level: number, openStatus: 'open' | 'close' },
    data: Array<ClassifySimple>,
  },
  context: Array<Context>,
  things: Array<ThingSimple>,
  inbox: Array<ThingSimple>,
  isChange: boolean,
  isUpload: boolean,
  thing: Thing,
};

const initialState: Things = {
  classify: {
    isopenRange: { level: -1, openStatus: 'open' },
    data: [
      {
        id: '1',
        pid: '',
        level: 0,
        classifyType: 'classify',
        actionType: 'other',
        title: '1',
        createdTime: 1000,
        updatedTime: 1000,
      },
      {
        id: '2',
        pid: '1',
        level: 1,
        classifyType: 'classify',
        actionType: 'parallet',
        title: '2',
        createdTime: 1000,
        updatedTime: 1000,
      },
      {
        id: '2.1',
        pid: '2',
        level: 2,
        classifyType: 'action',
        actionType: 'parallet',
        title: '2.1',
        createdTime: 1000,
        updatedTime: 1000,
      },
      {
        id: '3',
        pid: '',
        level: 0,
        classifyType: 'classify',
        actionType: 'other',
        title: '3',
        createdTime: 1000,
        updatedTime: 1000,
      },
      {
        id: '4',
        pid: '',
        level: 0,
        classifyType: 'classify',
        actionType: 'other',
        title: '4',
        createdTime: 1000,
        updatedTime: 1000,
      },
    ],
  },
  context: [],
  inbox: [],
  things: [],
  isChange: false,
  isUpload: false,
  thing: null,
};

export default handleActions(
  {
    [CHANGE_CLASSIFY]: (state, action: ChangeClassifyAction) => {
      return produce(state, (draft) => {
        if (!action || !draft) return;
        // console.log(action.payload);
        const realId = action.payload.id.split('-')[1];
        const index = draft.classify.data.findIndex(i => i.id === realId);
        const item = fromJS(draft.classify.data).find((obj) => {
          return obj.get('id') === action.payload.id.split('-')[1];
        });
        // console.log(item);
        const newItem = item.update('title', value => action.payload.value);
        // console.log(`index:${index}`);
        draft.classify.data.splice(index, 1, newItem.toObject());
        // draft.classify.data = draft.classify.data;
      });
    },
  },
  initialState,
);
function* loadClassifySaga(action: LoadClassifyAction) {
  yield thingApis.getClassify('');
}
export function* RootSaga() {
  yield takeLatest(LOAD_CLASSIFY.REQUEST, loadClassifySaga);
}
